<?php

namespace yunj\core\control;

use yunj\core\Config;
use yunj\core\control\form\YunjFormButton;
use yunj\core\exception\GeneralException;
use yunj\core\control\table\cols\YunjCol;
use yunj\core\control\form\field\YunjField;
use yunj\core\control\table\YunjTableToolbar;
use yunj\core\control\table\YunjTableDefaultToolbar;

final class YunjControl {

    /**
     * 获取指定类型的组件配置（系统配置+自定义配置）
     * @param string $type fields、cols
     * @return array
     */
    private static function getControlConfigByType(string $type): array {
        static $systemControl, $customControl;
        if (!isset($systemControl)) $systemControl = Config::get('control.', []);
        if (!isset($customControl)) $customControl = yunj_config('control.', []);
        return $systemControl[$type] + $customControl[$type];
    }

    /**
     * 表格表头templet
     * @return array
     */
    private static function getTableColTempletArr(): array {
        static $templetArr;
        if (!isset($templetArr)) {
            $templetArr = [];
            $_templetArr = self::getControlConfigByType('cols');
            foreach ($_templetArr as $k => $v) {
                $templetArr[$k] = $v['args'];
                self::layModuleExtend('TableCol' . ucfirst($k), $v['module']);
            }
        }
        return $templetArr;
    }

    /**
     * 表格表头type
     * @return array
     */
    private static function getTableColTypeArr(): array {
        return [
            'normal' => '\\yunj\\core\\control\\table\\cols\\type\\Normal',
            'checkbox' => '\\yunj\\core\\control\\table\\cols\\type\\CheckBox',
            'data' => '\\yunj\\core\\control\\table\\cols\\type\\Data',
        ];
    }

    /**
     * 表单字段
     * @return array
     */
    private static function getFormFieldArr(): array {
        static $fieldArr;
        if (!isset($fieldArr)) {
            $fieldArr = [];
            $_fieldArr = self::getControlConfigByType('fields');
            foreach ($_fieldArr as $k => $v) {
                $fieldArr[$k] = $v['args'];
                self::layModuleExtend('FormField' . ucfirst($k), $v['module']);
            }
        }
        return $fieldArr;
    }

    /**
     * 设置/获取 layui扩展module
     * @param string $name
     * @param string $path
     * @return array
     */
    public static function layModuleExtend(string $name = '', string $path = '') {
        static $module;
        $module = $module ?? [];
        if (!$module) {
            self::getTableColTempletArr();
            self::getFormFieldArr();
        }
        if ($name) {
            $module[$name] = $path;
        } else {
            return $module;
        }
    }

    /**
     * 表单字段配置
     * @param array $args
     * @param string $formId 表单id
     * @return array<error,args>    [错误消息,正常参数]
     */
    public static function formField(array $args, string $formId) {
        $allowFieldArr = self::getFormFieldArr();
        $args['type'] = $args['type'] ?? 'text';
        // type为闭包函数时为自定义类型
        if ($args['type'] instanceof \Closure) {
            $args['html'] = call_user_func_array($args['type'], [$formId]);
            $args['type'] = 'custom';
        }
        /** @var YunjField $field */
        if (!($field = $allowFieldArr[$args['type']] ?? null)) return ["表单字段类型[type={$args['type']}]配置错误", null];
        return $field::check($args);
    }

    /**
     * 表单按钮配置
     * @param string $key
     * @param string|array $args
     * @return array<error,args>    [错误消息,正常参数]
     */
    public static function formButton(string $key, $args): array {
        return YunjFormButton::check($key, $args);
    }

    /**
     * 表格表头配置
     * @param string $key
     * @param array $args
     * @return array<error,args>    [错误消息,正常参数]
     */
    public static function tableCol(string $key, array $args): array {
        $allowTypeArr = self::getTableColTypeArr();
        $args['type'] = isset($args['type']) && isset($allowTypeArr[$args['type']]) ? $args['type'] : 'normal';

        // type!=normal
        if ($args['type'] != 'normal') {
            if (isset($args['templet'])) unset($args['templet']);
            /** @var YunjCol $col */
            $col = $allowTypeArr[$args['type']];
            return $col::check($key, $args);
        }

        // templet
        if (isset($args['templet'])) {
            $allowTempletArr = self::getTableColTempletArr();
            // type为闭包函数时为自定义模板
            if ($args['templet'] instanceof \Closure) {
                $args['html'] = call_user_func_array($args['templet'], []);
                $args['templet'] = 'custom';
            }
            /** @var YunjCol $col */
            if ($col = $allowTempletArr[$args['templet']] ?? null) return $col::check($key, $args);
        }

        // 始终返回常规的表头
        /** @var YunjCol $col */
        $col = $allowTypeArr['normal'];
        return $col::check($key, $args);
    }

    /**
     * 表格工具栏操作配置
     * @param array $args
     * @return array<error,args>    [错误消息,正常参数]
     */
    public static function tableToolbar(array $args): array {
        return YunjTableToolbar::check($args);
    }

    /**
     * 表格右侧工具栏配置
     * @param string|mixed $key
     * @param string|array $args
     * @return array<error,key,args>    [错误消息,键名,正常参数]
     */
    public static function tableDefaultToolbar($key, $args): array {
        return YunjTableDefaultToolbar::check($key, $args);
    }

}